<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2017/6/14
 * Time: 15:54
 */

namespace Weixin\Service;


use Common\Common\Service;
use Weixin\Component\User_weixin\UserWeixinComponent;
use Weixin\Exception\WeixinException;
use Weixin\Request\User_weixin\AddUserWeixinRequest;
use Weixin\Response\AddUserWeixinResponse;

class AddUserWeixinService implements Service
{
    public function run(AddUserWeixinRequest $request = null)
    {
        if ($request->issetUserId() == false) {
            throw new WeixinException(10001);
        }
        if ($request->issetWeixinId() == false) {
            throw new WeixinException(10001);
        }
        if ($request->verifyUserId() == false) {
            throw new WeixinException(10002);
        }
        if ($request->verifyWeixinId() == false) {
            throw new WeixinException(10002);
        }
        if ($request->IsUserIdInRange() == false) {
            throw new WeixinException(10003);
        }
        if ($request->IsWeixinIdInRange() == false) {
            throw new WeixinException(10003);
        }

        $weixin_id = $request->getWeixinId();
        $user_id = $request->getUserId();
        $data['weixin_id'] = $weixin_id;
        $data['user_id'] = $user_id;
        $component = new UserWeixinComponent();
        $response = new AddUserWeixinResponse();
        try {
            $id = $component->addUserWeixin($data);
            if (!$id) {
                $response->setItIsNull();
            }
        } catch (WeixinException $e) {
            throw new WeixinException($e->getMessage(), $e->getCode());
        }
        return $response;
    }
}